using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Tools
{
    public class DbContext
    {
        public string Server = string.Empty;
        public string Database = string.Empty;
        public string ConnectionString = string.Empty;
    }

    /// <summary>
    /// Context Object Explorer
    /// </summary>
    public static class ObjectExplorerContext
    {
        public static DbContext Parse(string context)
        {
            DbContext dbContext = new DbContext();
            Regex re;
            Match m;

            char[] sep = new char[] { '/' };
            char[] equalSep = new char[] { '=' };
            char[] apostrSep = new char[] { '\'' };

            string[] items = context.Split(sep);
            string[] equalItems;
            string[] apostrItems;

            foreach (string item in items)
            {
                if (item.ToLower().StartsWith("server"))
                {
                    re = new Regex(".*Server\\[@Name='(.*?)']?");
                    if (re.Match(item).Success)
                    {
                        equalItems = item.Split(equalSep);
                        apostrItems = equalItems[1].Split(apostrSep);

                        dbContext.Server = apostrItems[1];

                        dbContext.ConnectionString = UtilitySqlTools.Current.ConnectionString();
                    }
                }
                else if (item.ToLower().StartsWith("database"))
                {
                    re = new Regex(".*Database\\[@Name='(.*?)']?");
                    if (re.Match(item).Success)
                    {
                        equalItems = item.Split(equalSep);
                        apostrItems = equalItems[1].Split(apostrSep);

                        dbContext.Database = apostrItems[1];
                    }
                }
            }

            return dbContext;
        }

        public static bool AreDifferent(DbContext older, DbContext newer)
        {
            if (older.Database != newer.Database || older.Server != newer.Server)
            {
                return true;
            }

            return false;
        }
    }
}

